#pragma once
#include <iostream>
#include <string>
#include <functional>
#include "sock.hpp"

namespace selectServer_wmh
{
    static const int defaultport = 8083;
    static const int fdnum = sizeof(fd_set) * 8; // 文件描述符数组大小
    static const int defaultfd = -1;

    using func_t = std::function<std::string(const std::string &)>;

    class SelectServer
    {

    public:
        SelectServer(func_t f, int port = defaultport)
            : func(f), _port(port), _listensock(-1), fdarray(nullptr)
        {
        }

        void Print()
        {
            std::cout << "fd list: ";
            for (int i = 0; i < fdnum; i++)
            {
                if (fdarray[i] != defaultfd)
                    std::cout << fdarray[i] << " ";
            }
            std::cout << std::endl;
        }

        void Accepter(int _listensock)
        {
            logMessage(DEBUG, "Accepter in");
            std::string clientip;
            uint16_t clientport = 0;
            int sock = Sock::Accept(_listensock, &clientip, &clientport); // accept = 等 + 获取
            if (sock < 0)
                return;
            logMessage(NORMAL, "accept success [%s:%d]", clientip.c_str(), clientport);
            // 这里不能直接recv/read，只有select有资格检测时间按是否就绪
            // 需要将新的sock交给select
            // 本质就是添加到fdarray数组
            int i = 0;
            for (; i < fdnum; ++i) // 找到空的的位置
            {
                if (fdarray[i] != defaultfd)
                    continue;
                else
                    break;
            }
            if (i == fdnum) // 数据已满
            {
                logMessage(WARNING, "server if full, please wait");
                close(sock);
            }
            else
            {
                fdarray[i] = sock; // fd添加进数组
            }
            Print();
            logMessage(DEBUG, "Accepter out");
        }

        void Recver(int sock, int pos)
        {
            logMessage(DEBUG, "in recver");

            // 1.读取request，有bug
            char buffer[1024];
            ssize_t s = recv(sock, buffer, sizeof(buffer) - 1, 0); // 不会被阻塞
            if (s > 0)
            {
                buffer[s] = 0;
                logMessage(NORMAL, "client# %s", buffer);
            }
            else if (s == 0)//客户端退出
            {
                close(sock);
                fdarray[pos] = defaultfd;
                logMessage(NORMAL, "client quit");
                return;
            }
            else
            {
                close(sock);
                fdarray[pos] = defaultfd;
                logMessage(ERROR, "client quit: %s", strerror(errno));
                return;
            }
            // 2. 处理request
            std::string response = func(buffer);

            // 3. 返回response
            write(sock, response.c_str(), response.size()); // 有bug

            logMessage(DEBUG, "out Recver");
        }

        void HandlerReadEvent(fd_set &rfds)
        {
            for (int i = 0; i < fdnum; ++i)
            {
                // 过滤非法的fd
                if (fdarray[i] == defaultfd)
                    continue;

                // 正常的
                if (FD_ISSET(fdarray[i], &rfds) && fdarray[i] == _listensock) // listensock负责接收
                {
                    Accepter(_listensock);
                }
                else if (FD_ISSET(fdarray[i], &rfds)) // 其余的就绪sock负责读取
                {
                    Recver(fdarray[i], i);
                }
                else
                {
                }
            }
        }

        void initServer()
        {
            _listensock = Sock::CreateSocket();
            Sock::Bind(_listensock, _port);
            Sock::Listen(_listensock);
            // 初始化文件描述符数组
            fdarray = new int[fdnum];
            for (int i = 0; i < fdnum; ++i)
            {
                fdarray[i] = defaultfd;
            }
            // 目前只有它，先把listensock存进去
            fdarray[0] = _listensock;
        }
        void start()
        {
            for (;;)
            {
                fd_set rfds;    // 文件描述符集
                FD_ZERO(&rfds); // 清楚所有的位图数据

                int maxfd = fdarray[0];
                // 遍历查找最大的文件描述符和有效文件描述符
                for (int i = 0; i < fdnum; ++i)
                {
                    if (fdarray[i] == defaultfd)
                        continue;
                    FD_SET(fdarray[i], &rfds); // 将有效文件描述符设置进集合中
                    if (maxfd < fdarray[i])
                        maxfd = fdarray[i]; // 更新所有fd中最大的fd
                }

                logMessage(NORMAL, "max fd is: %d", maxfd);

                int n = select(maxfd + 1, &rfds, nullptr, nullptr, nullptr); // 阻塞
                switch (n)
                {
                case 0: // 超时没有返回
                    logMessage(NORMAL, "timeout...");
                    break;
                case -1: // 错误
                    logMessage(WARNING, "select error, code: %d, err string: %s", errno, strerror(errno));
                    break;

                default:
                    // 说明有事件就绪了
                    logMessage(NORMAL, "have event ready!");
                    HandlerReadEvent(rfds);
                    break;
                }
            }
        }
        ~SelectServer()
        {
            if (_listensock < 0)
                close(_listensock);
            if (fdarray)
                delete[] fdarray;
        }

    private:
        int _port;
        int _listensock;
        int *fdarray;
        func_t func;
    };
}